package com.idata.controller;

import cn.hutool.http.HttpUtil;
import com.idata.model.request.ImgUrlRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

@Controller
public class ImgController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ImgController.class);

    @RequestMapping(path = "/imgRedirect", method = RequestMethod.POST)
    public void imgRedirect(HttpServletResponse response, @RequestBody ImgUrlRequest imgUrlRequest) throws IOException {
        // 使用Hutool进行HTTP请求，获取图片数据
        LOGGER.info("图片请求路径为 {}", imgUrlRequest.getImgUrl());
        byte[] imageData = HttpUtil.downloadBytes(imgUrlRequest.getImgUrl());
        LOGGER.info("图片size is {}", imageData.length);
        OutputStream os = response.getOutputStream();
        os.write(imageData);
    }

}
